from django.http import JsonResponse
from meiduo_move_server.utils import request_utils
from meiduo_move_server.utils import img_utils
from meiduo_move_server.utils.mysql_utils import MySQLUtils
from meiduo_move_server import project_constants as p_const
from meiduo_move_server.utils import data_type_change_utils
from user.utils import jwt_utils


def addUserReceiveAddressInfo(req):
    """
    添加用户收货地址信息
    """
    body = request_utils.getPostDataToDict(req.body)
    token = jwt_utils.get_payload(body.get('token'))
    userId = token.get('userId')
    id = body.get('id')
    receiveName = body.get('receiveName')
    receiveTelephone = body.get('receiveTelephone')
    receiveAddress = body.get('receiveAddress')
    isDefault = body.get('isDefault')
    # print(body)
    if isDefault:
        sql = """
        UPDATE user_receive_address_info SET is_default = FALSE;
        """
        row_count = MySQLUtils.update(sql)
    sql = None
    row_count = None
    if id is not None:
        sql = """
        UPDATE user_receive_address_info
        SET receive_name = %s, receive_telephone = %s, receive_address = %s, is_default = %s, user_account_info_id = %s
        WHERE id = %s;
        """
        row_count = MySQLUtils.update(sql, (receiveName, receiveTelephone, receiveAddress, isDefault, userId, id))
    else:
        sql = """
        INSERT INTO user_receive_address_info(receive_name, receive_telephone, receive_address, is_default, user_account_info_id)
        VALUES (%s, %s, %s, %s, %s);
        """
        row_count = MySQLUtils.update(sql, (receiveName, receiveTelephone, receiveAddress, isDefault, userId))
    if row_count < 1:
        return JsonResponse({
            'mark': p_const.MARK_ERROR,
            'message': '收货地址保存失败'
        })
    return JsonResponse({
        'mark': p_const.MARK_SUCCESS,
        'message': '收货地址保存成功'
    })


def getUserReceiveAddressInfo(req):
    """
    获取用户的收货地址信息
    """
    body = request_utils.getPostDataToDict(req.body)
    token = jwt_utils.get_payload(body.get('token'))
    userId = token.get('userId')
    sql = """
    SELECT * FROM user_receive_address_info WHERE user_account_info_id = %s ORDER BY id DESC;
    """
    res_data = MySQLUtils.select(sql, (userId,))
    if res_data.get('row_count') < 1:
        return JsonResponse({
            'mark': p_const.MARK_ERROR,
            'message': '暂无收货地址信息'
        })
    userReceiveAddressInfo = data_type_change_utils.tuple2dict(
        ['id', 'name', 'tel', 'address', 'isDefault', 'userAccountInfoId', 'isSelected'],
        res_data.get('data')
    )
    return JsonResponse({
        'mark': p_const.MARK_SUCCESS,
        'message': '获取收货地址信息成功',
        'data': userReceiveAddressInfo
    })


def getUserReceiveAddressInfoById(req):
    """
    获取用户的收货地址信息
    """
    id = req.GET.get('id')
    sql = """
    SELECT * FROM user_receive_address_info WHERE id = %s;
    """
    res_data = MySQLUtils.select(sql, (id,))
    if res_data.get('row_count') < 1:
        return JsonResponse({
            'mark': p_const.MARK_ERROR,
            'message': '暂无收货地址信息'
        })
    userReceiveAddressInfo = data_type_change_utils.tuple2dict(
        ['id', 'name', 'tel', 'address', 'isDefault', 'userAccountInfoId'],
        res_data.get('data')
    )
    return JsonResponse({
        'mark': p_const.MARK_SUCCESS,
        'message': '获取收货地址信息成功',
        'data': userReceiveAddressInfo[0]
    })


def getDefaultUserReceiveAddressInfo(req):
    """
    获取用户的收货地址信息
    """
    body = request_utils.getPostDataToDict(req.body)
    token = jwt_utils.get_payload(body.get('token'))
    userId = token.get('userId')
    # print(userId)
    sql = """
    SELECT * FROM user_receive_address_info WHERE user_account_info_id = %s AND is_default = TRUE;
    """
    res_data = MySQLUtils.select(sql, (userId,))
    if res_data.get('row_count') < 1:
        # 没有默认收货地址默认选取最新添加的
        sql = """
        SELECT * FROM user_receive_address_info WHERE user_account_info_id = %s ORDER BY id DESC LIMIT 1;
        """
        res_data = MySQLUtils.select(sql, (userId,))
        if res_data.get('row_count') < 1:
            return JsonResponse({
                'mark': p_const.MARK_ERROR,
                'message': '暂无收货地址',
            })
    userReceiveAddressInfo = data_type_change_utils.tuple2dict(
        ['id', 'name', 'tel', 'address', 'isDefault', 'userAccountInfoId', 'isSelected'],
        res_data.get('data')
    )
    # print(userReceiveAddressInfo)
    return JsonResponse({
        'mark': p_const.MARK_SUCCESS,
        'message': '获取收货地址信息成功',
        'data': userReceiveAddressInfo[0]
    })


def deleteUserReceiveAddressInfoById(req):
    """
    获取用户的收货地址信息
    """
    id = req.GET.get('id')
    sql = """
    DELETE FROM user_receive_address_info WHERE id = %s;
    """
    row_count = MySQLUtils.update(sql, (id,))
    if row_count < 1:
        return JsonResponse({
            'mark': p_const.MARK_ERROR,
            'message': '删除收货地址信息失败'
        })
    return JsonResponse({
        'mark': p_const.MARK_SUCCESS,
        'message': '删除收货地址信息成功'
    })